﻿using IdentityServer4.Models;
using IdentityServer4.Validation;
using Microsoft.AspNetCore.Identity;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Identity;

namespace Bridge.AuthServer.Host
{
    public class UserNameGrantValidator : IExtensionGrantValidator
    {
        public string GrantType => "username";
        private readonly UserManager<Volo.Abp.Identity.IdentityUser> _usermanager;
        private readonly IdentityUserManager _identityUserManager;

        public UserNameGrantValidator(UserManager<Volo.Abp.Identity.IdentityUser> usermanager, IdentityUserManager identityUserManager)
        {
            _usermanager = usermanager;
            this._identityUserManager = identityUserManager; 
        }
        public  Task ValidateAsync(ExtensionGrantValidationContext context)
        {
            var username = context.Request.Raw.Get("username");

            var user = _usermanager.FindByNameAsync(username).Result;
            if (user ==null)
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "用户未注册");
                          return Task.FromResult(1);

            }

 


            context.Result = new GrantValidationResult(
                        subject: user.Id.ToString(),
                        authenticationMethod: GrantType);
            return Task.FromResult(0);
        }
    }
}
